package com.chen10.gobang.service.impl;

import com.chen10.gobang.common.constants.EmailConstants;
import com.chen10.gobang.common.enums.email.EmailTypeEnum;
import com.chen10.gobang.common.enums.response.ErrorEnum;
import com.chen10.gobang.common.exception.BusinessException;
import com.chen10.gobang.common.utils.EmailUtil;
import com.chen10.gobang.common.utils.RedisUtil;
import com.chen10.gobang.common.utils.RegexUtils;
import com.chen10.gobang.mapper.UserMapper;
import com.chen10.gobang.model.vo.SendEmailVO;
import com.chen10.gobang.service.EmailCodeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
public class EmailCodeServiceImpl implements EmailCodeService {

    @Resource
    private EmailUtil emailUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserMapper userMapper;

    @Override
    public void sendCode(SendEmailVO sendEmailVO) {
        String email = sendEmailVO.getEmail();
        Integer type = sendEmailVO.getType();
        String key = null;

        //校验邮箱
        if(!RegexUtils.isValidEmail(email)){
            throw new BusinessException(ErrorEnum.EMAIL_INVALID);
        }
        //判断类型
        if(type.equals(EmailTypeEnum.REGISTER.getType())){
            //注册，判断邮箱是否已经被注册
            if(userMapper.selectByEmail(email) != null){
                throw new BusinessException(ErrorEnum.EMAIL_ALREADY_EXISTS);
            }
            key = EmailConstants.REGISTER_CODE_KEY_PREFIX + email;

        }else{
            //忘记密码，判断邮箱是否存在
            if(userMapper.selectByEmail(email) == null){
                throw new BusinessException(ErrorEnum.EMAIL_NOT_FOUND);
            }

            key = EmailConstants.FORGET_PASSWORD_CODE_KEY_PREFIX + email;
        }

        //检查缓存是否已经有验证码了
        if(redisUtil.get(key) != null){
            throw new BusinessException(ErrorEnum.EMAIL_CODE_ALREADY_EXITED);
        }
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(1000000));

        // 发送邮件
        try {
            emailUtil.sendEmail(email, code, type);
        }catch (Exception e){
            throw new BusinessException(ErrorEnum.EMAIL_SEND_FAILED);
        }
        // 将验证码保存到Redis，有效期5分钟
        redisUtil.setex(key, code, 5, TimeUnit.MINUTES);
    }

}
